using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

using TInput = System.Xml.XmlDocument;
using TOutput = WindowsGame1Content.Tilemap.TilemapContent;
using System.Xml;

namespace WindowsGame1Content.Tilemap
{
    [ContentProcessor(DisplayName = "Tile Map Processor")]
    public class TilemapProcessor : ContentProcessor<TInput, TOutput>
    {
        public override TOutput Process(TInput input, ContentProcessorContext
        context)
        {
            TilemapContent tileMap = new TilemapContent();
            XmlNode rootNode = input.FirstChild;
            if (rootNode.Name != "TileMap")
            {
                throw new Exception("Invalid tile map format!");
            }
            tileMap.mapWidth = Int32.Parse(rootNode.Attributes["Width"].Value);
            tileMap.mapHeight = Int32.Parse(rootNode.Attributes["Height"].Value);
            XmlNode layersNode = rootNode.FirstChild;
            if (layersNode.Name != "Layers")
            {
                throw new Exception("Invalid tile map format!");
            }
            MapLayer layer;
            foreach (XmlNode node in layersNode.ChildNodes)
            {
                if (node.Name == "Layer")
                {
                    try
                    {
                        layer = new MapLayer(tileMap.mapWidth, tileMap.mapHeight);
                        LoadLayer(node, layer, tileMap.mapWidth);
                        tileMap.layers.Add(layer);
                    }
                    catch
                    {
                        throw new Exception("Error reading in map layer!");
                    }
                }
            }
            return tileMap;
        }
        private void LoadLayer(XmlNode layerNode, MapLayer layer, int mapWidth)
        {
            int rowCount = 0;
            foreach (XmlNode node in layerNode)
            {
                if (node.Name == "Row")
                {
                    string row = node.InnerText;
                    row.Trim();
                    string[] cells = row.Split(' ');
                    for (int i = 0; i < mapWidth; i++)
                        layer.SetTile(i, rowCount, Int32.Parse(cells[i]));
                    rowCount++;
                }
            }
        }
    }
}